<template>
  <v-container class="pa-0">
    <v-row>
      <v-col cols="12" sm="6" md="4" lg="3">
        <v-hover v-slot:default="{ hover }">
        <v-card :disabled="multiple ? files.length === maximum : files.length === 1 " :elevation="hover ? 12 : 2">
          <!-- <v-card-text> -->
            <v-input
            height="160"
            :messages="inputMessages"
            :error="false"
            :error-messages="inputErrorMessages"
            :error-count="inputMsgCount">
              <file-upload
              style="width:100%;"
              :multiple="multiple"
              :maximum="maximum"
              ref="upload"
              v-model="files"
              :headers="headers"
              :post-action="SingleImageUploadApi"
              put-action=""
              :size="maxSize"
              :extensions="allowExt"
              @input-file="inputFile"
              @input-filter="inputFilter"
              :data="{water: water, module: moduleName}"
              >
                <v-btn block height="160" ><v-icon>add_photo_alternate</v-icon>
                {{files.length === maximum ? '已经够了': '点击上传'}}</v-btn>
                </file-upload>
            </v-input>
        <!-- </v-card-text>-->
        <v-card-actions>
          <!-- <v-checkbox disabled class="mt-0" hide-details :label="water ? '添加水印' : '不加水印'" color="primary" v-model="water"></v-checkbox> -->
        </v-card-actions>
        </v-card>
        </v-hover>
      </v-col>
      <v-col  cols="12" sm="6" md="4" lg="3" v-for="(item,index) in files" :key="item.id">
        <v-card :loading="item.active" :color="item.response.is_cover ? 'teal' : ''" class="lighten-2">
          <v-img :src="item.response.url" height="160"></v-img>
          <v-card-actions>
            <v-row justify="space-around" dense>
              <v-col><v-btn :disabled="!item.success" depressed block small color="info" @click.stop="previewFile(item)"><v-icon small>zoom_in</v-icon>预览</v-btn></v-col>
              <template v-if="multiple">
                <v-col v-if="item.response.is_cover"><v-btn :disabled="!item.success" depressed block small color="teal" class="darken-2" dark @click="cancelCoverFile(item)"><v-icon small>cancel</v-icon>取消封面</v-btn></v-col>
                <v-col v-else><v-btn :disabled="!item.success" depressed block small color="success" @click="setCoverFile(item)"><v-icon small>photo</v-icon>设置封面</v-btn></v-col>
              </template>
              <v-col><v-btn depressed block small color="warning" @click="deleteFile(index)"><v-icon small>delete</v-icon>删除</v-btn></v-col>
            </v-row>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>
    <v-row>
      <v-dialog
      v-model="previewVisible"
      width="60%"
      :fullscreen="previewFullscreen"
      >
      <v-container class="white pa-0" fluid v-if="previewFileItem">
        <v-row justify="space-between" dense>
          <v-col cols="6"><p class="pa-2 ma-0 subheading">{{previewFileItem.name}}</p></v-col>
          <v-spacer></v-spacer>
          <v-col cols="6">
            <v-btn  class="float-right" text color="primary" @click="previewVisible = false"><v-icon>close</v-icon>关闭</v-btn>
            <v-btn  class="float-right" text color="secondary" @click="previewFullscreen = !previewFullscreen"><v-icon>{{previewFullscreen ? 'fullscreen_exit':'fullscreen'}}</v-icon>{{previewFullscreen ? '退出全屏':'全屏显示'}}</v-btn>
          </v-col>
        </v-row>
        <v-row dense>
          <v-col class="pa-0"><v-img height="100%" :src="previewFileItem.response.url" contain></v-img></v-col>
        </v-row>
      </v-container>
    </v-dialog>
    </v-row>
  </v-container>
</template>
<script>
import VueUploadComponent from 'vue-upload-component'
import { SingleImageUploadApi } from '@/api/attachment'
import CustomFunc from '@/mixin/func.js'
export default {
  name: 'ImageUpload',
  props: {
    moduleName: {
      type: String,
      default: 'common'
    },
    label: {
      type: String,
      default: '图片上传'
    },
    hint: {
      type: String,
      default: ''
    },
    value: {
      type: Array,
      default: () => { return [] }
    },
    maxSize: {
      type: Number,
      default: 10 * 1024 * 1024
    },
    allowExt: {
      type: Array,
      default: () => { return ['jpeg', 'jpe', 'jpg', 'gif', 'png', 'webp'] }
    },
    multiple: {
      type: Boolean,
      default: true
    },
    maximum: {
      type: Number,
      default: 10
    },
    autoCover: {
      type: Boolean,
      default: true
    }
  },
  mixins: [ CustomFunc ],
  components: {
    'FileUpload': VueUploadComponent
  },
  data() {
    return {
      water: false,
      files: [],
      inputErrorMessages: [], // 错误消息
      previewVisible: false,
      previewFullscreen: false,
      previewFileItem: null,
      SingleImageUploadApi // 文件上传地址
    }
  },
  computed: {
    inputMessages: function() {
      return [
        '最多只能上传' + (this.multiple ? this.maximum : 1) + '张图片!'
        // '最大只能上传' + this.calcSize(this.maxSize) + '大小的图片'
      ] // 消息
    },
    inputError: function() {
      return this.inputErrorMessages.length > 0
    },
    inputMsgCount: function() {
      return Math.max(this.inputErrorMessages.length, this.inputMessages.length)
    },
    headers: function () {
      // return { 'Authorization': 'Bearer ' + this.$store.getters.token }
      return { 'Authorization': 'Bearer ' + this.$store.getters.token }
    },
    filesDataArray: function () {
      return this.files.map(e => {
        return e.response.url
      })
    }
  },
  watch: {
    value: function(newVal, oldVal) {
      if (this.files !== newVal && newVal !== null) {
        this.$refs.upload.clear()
        newVal.forEach(image => {
          let file = {
            active: false,
            name: image.filename,
            success: true,
            type: 'image/' + image.fileext,
            response: image,
            progress: '100.00',
            size: image.filesize
          }
          this.$refs.upload.add(file)
        })
      }
    }
  },
  mounted: function() {
    if (this.value !== null && this.value !== undefined) {
      this.value.forEach(image => {
        let file = {
          active: false,
          name: image.filename,
          success: true,
          type: 'image/' + image.fileext,
          response: image,
          progress: '100.00',
          size: image.filesize
        }
        this.$refs.upload.add(file)
      })
    }
  },
  methods: {
    clearErrorMessage: function() {
      this.inputErrorMessages = []
    },
    updateValue: function() {
      if (this.$refs.upload && this.$refs.upload.uploaded) {
        this.$emit('input', this.filesDataArray)
        this.clearErrorMessage()
      }
    },
    deleteFile: function(index) {
      this.files.splice(index, 1)
      this.updateValue()
    },
    previewFile: function(item) {
      this.previewFileItem = item
      this.previewVisible = true
    },
    setCoverFile: function(item) {
      this.files.forEach(e => (e.response.is_cover = false))
      item.response.is_cover = true
      this.updateValue()
    },
    cancelCoverFile: function(item) {
      item.response.is_cover = false
      this.updateValue()
    },
    /**
     * Has changed
     * @param  Object|undefined   newFile   只读
     * @param  Object|undefined   oldFile   只读
     * @return undefined
     */
    inputFile: function(newFile, oldFile) {
      // 自动上传
      if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
        if (!this.$refs.upload.active) {
          this.$refs.upload.active = true
        }
      }
      // 添加文件
      if (newFile && !oldFile) {
        // 添加文件
      }
      // 更新文件
      if (newFile && oldFile) {
        // 上传成功
        if (newFile.success !== oldFile.success) {
          if (this.files.length === 1 && this.autoCover) {
            newFile.response.is_cover = true
          }
          this.updateValue()
        }
        // 上传错误
        if (newFile.error !== oldFile.error) {
          // console.log('error', newFile.error, newFile)
          this.files.pop()
          this.inputErrorMessages.push('发生' + newFile.error + '错误')
        }
      }
    },
    /**
     * Pretreatment
     * @param  Object|undefined   newFile   读写
     * @param  Object|undefined   oldFile   只读
     * @param  Function           prevent   阻止回调
     * @return undefined
     */
    inputFilter: function (newFile, oldFile, prevent) {
      if (newFile && !oldFile) {
        const extStr = this.allowExt.join('|')
        const regExp = new RegExp('\\.(' + extStr + ')$', 'i')
        // eslint-disable-next-line
        if (!regExp.test(newFile.name)) {
          this.inputErrorMessages.push('不允许的上传类型！只允许上传' + extStr + '类型的图片文件')
          return prevent()
        }
        if (newFile.size > (this.maxSize)) {
          this.inputErrorMessages.push('图片尺寸过大(文件大小：' + this.calcSize(newFile.size) + ')！请选择文件大小为' + this.calcSize(this.maxSize) + '以下的图片进行上传！')
          return prevent()
        }
        // 判断个数
        if (this.multiple && this.files.length === this.maximum) {
          this.inputErrorMessages.push('最多上传' + this.maximum + '张图片！')
          return prevent()
        } else if (!this.multiple && this.files.length === 1) {
          this.inputErrorMessages.push('只能上传一张图片！')
          return prevent()
        }
      }
    }
  }
}
</script>
<style>
.v-messages__wrapper{
  padding: 0 10px 0 10px;
}
</style>
